/**
 * 页面错误捕捉
 */
import React from 'react';

export default class ErrorBoundary extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidCatch(error) {
    console.error(error.message);
    this.setState({ error });
  }

  render() {
    const { children } = this.props;
    const { error } = this.state;

    if (error) {
      const pattern = /Loading chunk (\d)+ failed/g;
      const isChunkLoadFailed = error.message.match(pattern);
      if (isChunkLoadFailed) {
        window.location.reload();
        return null;
      }
      return (
        <div
          style={{
            padding: 12,
            border: '1px solid red',
            borderRadius: 4,
            marginBottom: 12,
          }}
        >
          <h3>Render Custom Component Failed</h3>
          <code>{error.message}</code>
        </div>
      );
    }

    return children;
  }
}

export function withErrorBoundary(Component) {
  return (props) => (
    <ErrorBoundary>
      <Component {...props} />
    </ErrorBoundary>
  );
}
